package com.ks.winterwarmimage;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListPopupWindow;
import android.widget.ListView;
import android.widget.TextView;

import com.ks.winterwarmimage.adapter.AccountAdapter;
import com.ks.winterwarmimage.adapter.DevItem;
import com.ks.winterwarmimage.adapter.DeviceRecyclerAdapter;
import com.ks.winterwarmimage.database.DatabaseManager;
import com.ks.winterwarmimage.menu.DropMenu;
import com.ks.winterwarmimage.mqtt.MqttMag;
import com.ks.winterwarmimage.mqtt.MsgMqttService;
import com.ks.winterwarmimage.utils.ActivityUtil;
import com.ks.winterwarmimage.utils.BasicsUtil;
import com.ks.winterwarmimage.utils.CmdDataPacket;
import com.ks.winterwarmimage.utils.Constants;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends BaseActivity implements View.OnClickListener, DeviceRecyclerAdapter.OnItemClickListener {
    private static final String TAG="MainActivity";
    private static final String MQTT_SERVER_URI="tcp://mqtt.eclipseprojects.io:1883";
    private static final String base_topic="WinterWarmImage/dev/";
    private static final String subscribe_topic=base_topic+"#";
    ///////////////////////////弹出菜单项目关键字/////////////////////////////
    private static final String MENU_KEY_ACCOUNT="menu_account";
    private static final String MENU_KEY_LOAD_BIND = "menu_load_bind";
    private static final String MENU_KEY_NETWORK_CONFIG="menu_network_config";

    private TextView textTitle;
    private ImageView imgMenu;
    private RecyclerView recyclerDevView;
    private DeviceRecyclerAdapter  mAdapter;
    private List<DevItem> devList=new ArrayList<>();
    private String accountID=null;
    private DropMenu mMainDropMenu=null;
    private boolean isPause=false;
    private Runnable actionRunnable=null;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        textTitle=findViewById(R.id.text_main_title);
        imgMenu=findViewById(R.id.img_menu);
        accountID=DatabaseManager.getCurrentAccount();   //得到当前账号
        if(accountID!=null) {
            textTitle.setText(accountID);
        }else{
            textTitle.setText(R.string.app_name);
        }
        recyclerDevView=findViewById(R.id.grid_dev);
        recyclerDevView.setItemAnimator(null); // 禁用动画效果(防止数据变更导致闪烁)
        setHeadView();                           //设置标题栏背景视图
        initAdapter();                           //载入设备列表
        initRightMenu();                         //初始化右上角菜单
        bindMqttService();                       //绑定MQTT服务
        checkSelfBlePermission(false);
        imgMenu.setOnClickListener(this);
        findViewById(R.id.img_account_select).setOnClickListener(this);
    }

    @Override
    protected void onDestroy() {
        unTimingSyncState();
        MsgMqttService.mqttDisconnect();
        unMqttBroadcastReceiver();
        unbindMqttService();
        super.onDestroy();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode==RESULT_CODE){
            if(resultCode==RESULT_CODE+1) {   //注册和载入已绑定设备时的返回
                accountID= DatabaseManager.getCurrentAccount();
                textTitle.setText(accountID);
                initAdapter();    //重新载入设备列表
            }else if(resultCode==RESULT_CODE+2) {
               String account_ID= DatabaseManager.getCurrentAccount();
               if(!account_ID.equalsIgnoreCase(accountID)){
                   accountID= account_ID;
                   textTitle.setText(accountID);
               }
               initAdapter();    //重新载入设备列表
            }else if(resultCode==RESULT_CODE+3) {
                initAdapter();    //重新载入设备列表
            }
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        isPause=true;
        unTimingSyncState();
    }

    @Override
    protected void onResume() {
        super.onResume();
        isPause=false;
        publishSyncState();
    }

    @Override
    protected void onMqttServiceConnected() {
        super.onMqttServiceConnected();
        if(!MsgMqttService.getMqttConnect()) {
            MsgMqttService.mqttConnect(MQTT_SERVER_URI, MsgMqttService.DEF_MQTT_USER, MsgMqttService.DEF_MQTT_PWD);
        }
    }
    @Override
    protected void onMqttConnectionChange(@MqttCommandState int commandState) {
        super.onMqttConnectionChange(commandState);
        //先初始化所有设备状态为离线
        for(DevItem item:devList){
            item.devStatus=DevItem.DeviceStatus.OFF_LINE;
        }
        mAdapter.notifyItemRangeChanged(0,devList.size());
        if(commandState==MqttCommandState.MQTT_CONNECT_SUCCESS){   //连接成功
            //订阅所有设备主题
            if(MsgMqttService.subscribe(subscribe_topic,0)!=null){
                Log.e(TAG,"订阅成功"); //订阅成功
            }
            publishSyncState();
        }
    }
    @Override
    protected void onMessageArrived(MqttMag message) {
        super.onMessageArrived(message);
        message.getMessage();
        String id = message.getTopic().replace(base_topic, "");  //去掉基主题部分,得到最后的去除冒号的组ID
        String deviceId=BasicsUtil.addMacColon(id);    //将去除冒号的组ID加上冒号
        CmdDataPacket cmdDataPacket = CmdDataPacket.fromBytes(message.getMessage());
        if(cmdDataPacket!=null) {
            if (cmdDataPacket.command == CmdDataPacket.COM_SYNC_STATE
                    || cmdDataPacket.command == CmdDataPacket.COM_SYNC_STATE_ACK) {
                if (cmdDataPacket.data.length > 8) {
                    //表示小字节序字节顺序的常数。按此顺序，多字节值的字节从最低有效到最高有效排序。
                    byte[] temp_data = BasicsUtil.subByte(cmdDataPacket.data, 0, 4);
                    ByteBuffer buffer = ByteBuffer.wrap(temp_data).order(ByteOrder.LITTLE_ENDIAN);
                    float temp = buffer.getFloat();                      //温度
                    byte relayState = cmdDataPacket.data[4];              //继电器状态
                    boolean isAutoRelay = cmdDataPacket.data[5] == 1;    //是否由温度区间控制
                    byte brightness = cmdDataPacket.data[6];              //照明灯亮度
                    byte minTemp = cmdDataPacket.data[7];                 //高低温区间下限
                    byte maxTemp = cmdDataPacket.data[8];                 //高低温区间上限
                    for (int position = 0; position < devList.size(); position++) {
                        DevItem item = devList.get(position);
                        if (item.deviceId.equalsIgnoreCase(deviceId)) {
                            if(item.devStatus!= DevItem.DeviceStatus.ON_LINE
                                    ||item.temp != temp
                                    ||item.relayState != relayState) {   //这三个数据有一个不一致都需要刷新
                                item.devStatus = DevItem.DeviceStatus.ON_LINE;
                                item.temp = temp;
                                item.relayState = relayState;
                                item.isTempControlRelay = isAutoRelay;
                                item.brightness = brightness;
                                mAdapter.notifyItemChanged(position);
                            }
                            break;
                        }
                    }
                }
            } else if (cmdDataPacket.command == CmdDataPacket.COM_OFF ||
                    cmdDataPacket.command == CmdDataPacket.COM_OFF_ACK) {
                for (int position = 0; position < devList.size(); position++) {
                    DevItem item = devList.get(position);
                    if (item.deviceId.equalsIgnoreCase(deviceId)) {
                        item.devStatus = DevItem.DeviceStatus.OFF_LINE;
                        item.temp = 0;
                        item.brightness = 0;
                        mAdapter.notifyItemChanged(position);
                        break;
                    }
                }
            }
        }
        Log.e(TAG,"onMessageArrived: "+BasicsUtil.bytesToHexString(message.getMessage()));
    }
    @Override
    public void onClick(View view) {
        if(view.getId()==R.id.img_account_select){
            showListPopup((View) view.getParent());
        }else if(view.getId()==R.id.img_menu){
            //ActivityUtil.startActivity(this, DevRegisterActivity.class);
            mMainDropMenu.show();
        }
    }
    @Override
    public void onItemClick(View view, int position,@DeviceRecyclerAdapter.ClickId int clickId) {
        Bundle msg=new Bundle();
        msg.putString(Constants.KEY_MAC_ID,devList.get(position).deviceId);
        msg.putString(Constants.KEY_ACCOUNT_ID,accountID);
        msg.putString(Constants.KEY_DEV_NAME,devList.get(position).devName);
        if(clickId==DeviceRecyclerAdapter.ClickId.CLICK_ITEM){    //列表项目单击
            ActivityUtil.startActivity(MainActivity.this, DevControlActivity.class,REQUEST_CODE,msg);
        }else{       //列表项目网络重置按钮单击
            ActivityUtil.startActivity(MainActivity.this, DevRegisterActivity.class,REQUEST_CODE,msg);
        }
    }
   /**设置标题栏背景视图*/
    private void setHeadView(){
        ImageView imgHeadView = this.findViewById(R.id.image_background);
        View maskView = this.findViewById(R.id.mask_background);
        int screenWidth=BasicsUtil.getDisplaySize(this).x;      //屏幕宽度
        int imgWidth =imgHeadView.getDrawable().getIntrinsicWidth();   //图片宽度
        int imgHeight =imgHeadView.getDrawable().getIntrinsicHeight(); //图片高度
        //获取父视图布局参数
        ConstraintLayout.LayoutParams layoutParams = (ConstraintLayout.LayoutParams) imgHeadView.getLayoutParams();
        float scale = (float) screenWidth / imgWidth;  //缩放比例
        layoutParams.width = (int) (imgWidth * scale); //进行缩放后的图片宽度
        layoutParams.height = (int) (imgHeight * scale);//进行缩放后的图片高度
        imgHeadView.setLayoutParams(layoutParams); //设置图片视图的布局参数
        maskView.setLayoutParams(layoutParams);  //设置蒙版视图的布局参数
    }

    /**初始化右上角弹出菜单*/
    private void initRightMenu(){
        mMainDropMenu=new DropMenu(this,imgMenu, Gravity.END);
        mMainDropMenu.addMenuItem(MENU_KEY_ACCOUNT,R.string.account_manage,R.drawable.ic_account_24dp);
        mMainDropMenu.addSplitLine(1);
        mMainDropMenu.addMenuItem(MENU_KEY_LOAD_BIND,R.string.load_bin_dev,R.drawable.ic_load_24dp);
        mMainDropMenu.addMenuItem(MENU_KEY_NETWORK_CONFIG,R.string.network_config,R.drawable.ic_network_24);
        mMainDropMenu.setMenuItemIconTint(Color.GRAY);
        mMainDropMenu.setMenuItemBackgroundResource(R.drawable.button_style);//设置菜单项目背景样式
        mMainDropMenu.setOnMenuItemClickListener((item, view) -> {
            switch (item.getItemKey()){
                case MENU_KEY_ACCOUNT:
                    ActivityUtil.startActivity(MainActivity.this, AccountActivity.class,REQUEST_CODE);
                    break;
                case MENU_KEY_LOAD_BIND:
                    ActivityUtil.startActivity(MainActivity.this, LoadBindDevActivity.class,RESULT_CODE);
                    break;
                case MENU_KEY_NETWORK_CONFIG:
                    ActivityUtil.startActivity(MainActivity.this, DevRegisterActivity.class,REQUEST_CODE);
                    break;
            }
        });
    }
   /**初始化设备列表适配器*/
    @SuppressLint("Range")
    private void initAdapter(){
        Cursor cursor= DatabaseManager.rawQuery(Constants.TABLE_DEV,
                Constants.KEY_ACCOUNT_ID+"=?",new String[]{accountID});
        devList.clear();     //清空现有数据
        if(cursor!=null) {
            while (cursor.moveToNext()) {
                String id = cursor.getString(cursor.getColumnIndex(Constants.KEY_MAC_ID));
                String name = cursor.getString(cursor.getColumnIndex(Constants.KEY_DEV_NAME));
                DevItem item = new DevItem(id, name);
                devList.add(item);
            }
            cursor.close();
        }
        mAdapter=new DeviceRecyclerAdapter(devList);
        mAdapter.setOnItemClickListener(this);
        recyclerDevView.setLayoutManager(new GridLayoutManager(this,2));
        recyclerDevView.setAdapter(mAdapter);
    }
    /**显示账号列表弹窗*/
    private void showListPopup(View v) {
        AccountAdapter adapterAccount;
        List<AccountAdapter.Account> accountList=new ArrayList<>();
        List<String> accountIds= DatabaseManager.getAccountList();
        int currentPosition= DatabaseManager.getCurrentAccountPosition();

        float textWidth =0;//= textTitle.getPaint().measureText(text);
        if(accountIds!=null && accountIds.size()>0){
            for(int i=0;i<accountIds.size();i++){
                AccountAdapter.Account account=new AccountAdapter.Account(accountIds.get(i),i==currentPosition);
                accountList.add(account);
                //测量文本宽度
                float tempWidth=textTitle.getPaint().measureText(accountIds.get(i));
                if(tempWidth>textWidth)
                    textWidth=tempWidth;
            }
        }else{
            AccountAdapter.Account account=new AccountAdapter.Account(getString(R.string.no_account),false);
            accountList.add(account);
            //测量文本宽度
            textWidth=textTitle.getPaint().measureText(getString(R.string.no_account));
        }
        adapterAccount=new AccountAdapter(this,accountList,true);
        //创建列表对话框
        int width = (int) (textWidth+ BasicsUtil.dp2px(this,74));
        ListPopupWindow listPopupWindow=new ListPopupWindow(this);
        listPopupWindow.setBackgroundDrawable(getDrawable(R.drawable.rounded_corners));
        listPopupWindow.setAnchorView(v);//设置ListPopupWindow的锚点，关联mButton位置
        listPopupWindow.setWidth(width); //设置宽度
        listPopupWindow.setHeight(LinearLayout.LayoutParams.WRAP_CONTENT);
        listPopupWindow.setHorizontalOffset(10);
        listPopupWindow.setVerticalOffset(5);
        listPopupWindow.setModal(true);
        listPopupWindow.setAdapter(adapterAccount);
        listPopupWindow.setOnItemClickListener((parent, view, position, id)->{
            accountID=accountList.get(position).accountId;
            textTitle.setText(accountID);
            DatabaseManager.updateCurrentAccountPosition(position);
            initAdapter();    //重新载入设备列表
            publishSyncState();
            listPopupWindow.dismiss();
        });
        listPopupWindow.show();
    }
    /**
     * 向所有设备推送设备状态获取命令
     */
    private void publishSyncState(){
        if(MsgMqttService.getMqttConnect() && !isPause) {
            CmdDataPacket cmdDataPacket = new CmdDataPacket(CmdDataPacket.COM_SYNC_STATE, new byte[]{0x00});
            //向所有设备推送设备状态获取命令
            String topic = "WinterWarmImage/phone/global";
            MsgMqttService.publish(topic, cmdDataPacket.toBytes(), 0, false);
            timingSyncState();
        }
    }
    /**
     * 定时向所有设备推送设备状态获取命令
     */
    private void timingSyncState(){
        if(actionRunnable==null){
            actionRunnable= () -> publishSyncState();
        }
        recyclerDevView.postDelayed(actionRunnable, 60000);    //一分钟发送一次同步
    }
    /**
     * 取消定时向所有设备推送设备状态获取命令
     */
    private void unTimingSyncState(){
        if(actionRunnable!=null){
            recyclerDevView.removeCallbacks(actionRunnable);
            actionRunnable=null;
        }
    }
}